<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class ForumResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'icon' => mb_substr($this->icon, 0, 5) == 'icon-' ? $this->icon : "icon-{$this->icon}",
            'topic_count' => $this->topic_count,
            'comment_count' => $this->comment_count,
            'description' => $this->description,
            'topic_count_today' => $this->getStatValue('topicStatToday'),
            'comment_count_today' => $this->getStatValue('commentStatToday'),
        ];
    }

    private function getStatValue($relationship)
    {
        $loaded = $this->resource->relationLoaded($relationship);
        if ($loaded) {
            $model = $this->resource->{$relationship};
            return $model ? $model->value : 0;
        }
        return 0;
    }

}
